package com.example.bookstore.service.impl;

import com.example.bookstore.entity.BookUser;
import com.example.bookstore.enums.ResultEnum;
import com.example.bookstore.enums.TokenEnum;
import com.example.bookstore.exception.ResultException;
import com.example.bookstore.form.userform.LoginForm;
import com.example.bookstore.form.userform.RegisterForm;
import com.example.bookstore.form.userform.ChangePwdForm;
import com.example.bookstore.form.userform.UpdateUserForm;
import com.example.bookstore.mapper.BookUserMapper;
import com.example.bookstore.security.relam.UserRealm;
import com.example.bookstore.service.BookUserService;
import com.example.bookstore.token.LoginToken;
import com.example.bookstore.utils.PageUtil;
import com.example.bookstore.utils.PhoneCode;
import com.example.bookstore.utils.ResultVOUtil;
import com.example.bookstore.utils.TimeUtil;
import com.example.bookstore.vo.LoginVo;
import com.example.bookstore.vo.ResultVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.ParseException;
import java.util.*;

@Repository
public class BookUserServiceImpl implements BookUserService {

    @Autowired
    BookUserMapper bookUserMapper;

    @Override
    public ResultVO UserRegister(RegisterForm registerForm) throws ParseException {
        BookUser bookUser = new BookUser();

        bookUser.setuserName(registerForm.getUserName());
        bookUser.setPassword(registerForm.getPassword());
        bookUser.setGender(registerForm.getGender());
        bookUser.setEmail(registerForm.getEmail());
        bookUser.setTelephone(registerForm.getTelephone());
        bookUser.setIntroduce(registerForm.getIntroduce());
//        bookUser.setactivityCode(registerForm.getActivityCode());

        bookUser.setState(0); //默认未激活
        bookUser.setuserRole(1); // 默认普通用户
        bookUser.setregistTime(TimeUtil.getNowDateTime());

        try{
            bookUserMapper.UserRegister(bookUser);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }

        return ResultVOUtil.success(bookUser);
    }

    @Override
    public ResultVO UserChangePwd(ChangePwdForm changePwdForm) {
        try{
            bookUserMapper.UserChangePwd(changePwdForm);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success();
    }

    @Override
    public ResultVO UpdateUser(UpdateUserForm updateUserForm) {
        try{
            bookUserMapper.UpdateUser(updateUserForm);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return  ResultVOUtil.success();
    }

    @Override
    public ResultVO ActivityUser(String activity, Integer userId) {
        BookUser bookUser = new BookUser();
        try{
            bookUserMapper.ActivityUser(activity, userId);
            bookUser = bookUserMapper.SelectUserById(userId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success(bookUser);
    }

    @Override
    public ResultVO SelectUserById(Integer userId) {
        BookUser bookUser = new BookUser();

        try{
            bookUser = bookUserMapper.SelectUserById(userId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success(bookUser);
    }

    @Override
    public ResultVO SelectUserByName(String userName) {
        List<BookUser> bookUserList = new ArrayList<>();
        try{
            bookUserList = bookUserMapper.SelectUserByName(userName);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success(bookUserList);
    }

    @Override
    public ResultVO DeleteUserById(Integer userId) {
        try {
            bookUserMapper.DeleteUserById(userId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success();
    }

    @Override
    public ResultVO UserLogin(LoginForm loginForm) {

        Subject subject = SecurityUtils.getSubject();  //subject对象
        String realToken = (String) subject.getSession().getId();   //获取当前session当中的token
        System.out.println(realToken);

        //下面是当前尝试登录从而创建的一个token
        LoginToken loginToken = new LoginToken(loginForm.getUserName(),loginForm.getPassword(), TokenEnum.USER.toString());
        try {
            subject.login(loginToken);
            //尝试登录，没报错就说明成功，注意这个loginToken集成了UsernamePasswordToken
            //这里信息传递给realm进行验证
        }catch (UnknownAccountException e){
            throw new ResultException(ResultEnum.USER_NOT_EXIST);
        }catch (IncorrectCredentialsException e){
            throw new ResultException(ResultEnum.PASSWORD_ERROR);
        }catch (ResultException e){
            throw new ResultException(ResultEnum.USER_NOT_EXIST);
        }

        BookUser userInfo = bookUserMapper.SelectByLoginName(loginForm.getUserName());
        LoginVo loginVo = new LoginVo(userInfo,realToken);

        return ResultVOUtil.success (loginVo);
    }

    @Override
    public BookUser getCurrentUser() {
        Subject subject = SecurityUtils.getSubject ();   //创建一个subject对象，保存到ThreadContext的resources
        try {
            Collection collection = subject.getPrincipals ().fromRealm (UserRealm.getRealmName ()); //通过realm进行验证
            Iterator iterator = collection.iterator();
            BookUser user = new BookUser ();
            while(iterator.hasNext()) {
                Object object = iterator.next ();
                user = (BookUser) object;  //迭代集合返回用户信息
            }
            if (user==null){
                throw new ResultException(ResultEnum.SERVER_ERROR);
            }
            return user;
        }catch (NullPointerException e){
            throw new ResultException(ResultEnum.USER_NOT_LOGIN);
//            return ResultVOUtil.error(ResultEnum.USER_NOT_LOGIN);
        }
    }

    @Override
    public ResultVO UserLogout() {
        Subject subject = SecurityUtils.getSubject ();
        try{
            subject.logout ();
        }catch (Exception e){
            throw new ResultException(ResultEnum.SERVER_ERROR);
        }
        return ResultVOUtil.success ();
    }

    @Override
    public ResultVO ShowAllUser() {
        List<BookUser> bookUserList = new ArrayList<>();
        try {
            bookUserList = bookUserMapper.ShowAllUser();
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }

        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap = PageUtil.getMap(bookUserList);

        return ResultVOUtil.success(hashMap);
    }

    @Override
    public ResultVO UserLoginByTel(String telePhone,String code) {
        BookUser bookUser = new BookUser();
        System.out.println(telePhone);

        String isSuccess = null;
        isSuccess = PhoneCode.CheckCode(telePhone, code);
        if(isSuccess.equals("success")){
            try{
                bookUser = bookUserMapper.SelectUserByTel(telePhone);
            }catch (Exception e){
                e.printStackTrace();
                return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
            }

            LoginForm loginForm = new LoginForm();
            loginForm.setUserName(bookUser.getuserName());
            loginForm.setPassword(bookUser.getPassword());

            //接下是一样的登录
            Subject subject = SecurityUtils.getSubject();  //subject对象
            String realToken = (String) subject.getSession().getId();   //获取当前session当中的token
            System.out.println(realToken);

            //下面是当前尝试登录从而创建的一个token
            LoginToken loginToken = new LoginToken(loginForm.getUserName(),loginForm.getPassword(), TokenEnum.USER.toString());
            try {
                subject.login(loginToken);
                //尝试登录，没报错就说明成功，注意这个loginToken集成了UsernamePasswordToken
                //这里信息传递给realm进行验证
            }catch (UnknownAccountException e){
                throw new ResultException(ResultEnum.USER_NOT_EXIST);
            }catch (IncorrectCredentialsException e){
                throw new ResultException(ResultEnum.PASSWORD_ERROR);
            }catch (ResultException e){
                throw new ResultException(ResultEnum.USER_NOT_EXIST);
            }

            BookUser userInfo = bookUserMapper.SelectByLoginName(loginForm.getUserName());
            LoginVo loginVo = new LoginVo(userInfo,realToken);

            return ResultVOUtil.success (loginVo);
        }else {
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }

    }

}
